<?php
//加载项目扩展函数
function m($m) {
    $fileUri = 模块目录.DIRECTORY_SEPARATOR.$m.'.php';
    if (is_file($fileUri))include_once $fileUri;
}
function c($key1 = null,$key2 = null) {
    static $config = null;
    if ($config == null) {
        $config = 配置信息(配置文件);
    }
    if (is_null($key1)) {
        return $config;
    }
    if (is_null($key2)) {
        if (isset($config[$key1])) {
            return $config[$key1];
        }
        return null;
    }
    if (isset($config[$key1][$key2])) {
        return $config[$key1][$key2];
    }
    return null;
}
//获得视图的url地址，用于include
function showTpl($tplName = null) {
    sm('Mtpl');
    $config = c('tpl');
    $config['tplcachedir'] = 缓存目录.换行.$config['tplcachedir'].换行;
    $config['tpldir'] = 模板目录.换行;
    $tplUrl = (new Mtpl($config))->geturl($tplName);
    if (is_file($tplUrl)) {
        return($tplUrl);
    }
}
//加密解密函数
function lockString($string,$operation,$key = 'mtfy') {
    if ($operation == 'D') {
        $string = str_replace(array('-01.-','-02.-','-03.-'),array('%','/','+'),$string);
    }
    $key = md5($key);
    $key_length = strlen($key);
    $string = $operation == 'D'?base64_decode($string):substr(md5($string.$key),0,8).$string;

    $string_length = strlen($string);
    $rndkey = $box = array();
    $result = '';
    for ($i = 0;$i <= 255;$i++) {
        $rndkey[$i] = ord($key[$i%$key_length]);
        $box[$i] = $i;
    }
    for ($j = $i = 0;$i < 256;$i++) {
        $j = ($j+$box[$i]+$rndkey[$i])%256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    for ($a = $j = $i = 0;$i < $string_length;$i++) {
        $a = ($a+1)%256;
        $j = ($j+$box[$a])%256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result.= chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
    }
    if ($operation == 'D') {
        if (substr($result,0,8) == substr(md5(substr($result,8).$key),0,8)) {
            return substr($result,8);
        } else {
            return'';
        }
    } else {
        return str_replace(array('=','%','/','+'),array('','-01.-','-02.-','-03.-'),base64_encode($result));
    }
}
//加载数据库框架
function mdb($config = NULL) {
    if (isset($GLOBALS['mdb']))return $GLOBALS['mdb'];
    sm('Medoo');
    return $GLOBALS['mdb'] = new Medoo\Medoo($config??c('db'));
}
//session
function startSession() {
    $sessionConfig = c('session');
    switch ($sessionConfig['type']) {
        case 'memcache' :
            ini_set("session.save_handler", "memcache");
            ini_set("session.save_path", $sessionConfig['host']);
            break;
        case 'redis':
            ini_set("session.save_handler", "redis");
            ini_set("session.save_path", $sessionConfig['host']);
            break;
        default:
            $dir = 缓存目录.DIRECTORY_SEPARATOR.$sessionConfig['dir'].DIRECTORY_SEPARATOR;
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }
            session_save_path($dir);
    }
    session_start();
    session_write_close();
}
//session  (名字,值)
function session() {
    $numargs = func_num_args();
    $args = func_get_args();
    if ($numargs == 1) {
        if (isset($_SESSION[$args[0]])) {
            return $_SESSION[$args[0]];
        }
        return null;
    }
    if ($numargs >= 2) {
        @session_start();
        if($args[1]===null){
            unset($_SESSION[$args[0]]);
        }else{
            $_SESSION[$args[0]] = $args[1];
        }
        session_write_close();
    }
}
//cookie设置
function cookie() {
    $numargs = func_num_args();
    $args = func_get_args();
    if ($numargs == 1) {
        if (isset($_COOKIE[$args[0]])) {
            return $_COOKIE[$args[0]];
        }
        return null;
    }
    if ($numargs >= 2) {
        if ($args[1] === null) {
            setcookie($args[0], 'null', time() - 1000, '/');
            return;
        }
        $expire = @$args[2]?? 31536000;
        $expire += time();
        @setcookie($args[0], $args[1], $expire, '/');
        $_COOKIE[$args[0]] = $args[1];
    }
}
//数据缓存
function initCache() {
    if ($GLOBALS['cache']) {
        return $GLOBALS['cache'];
    }
    sm(c('cache','type').'Cacher');
    $GLOBALS['cache'] = (c('cache','type').'Cacher')::getInstance(c('cache'));
}
function cache($name,$queryMethod = '',$data = '',$update = false, $timer = 3600,$isSuper = true) {
    if (c('cache','start') == false) {
        return is_object($queryMethod)?(empty($data)?$queryMethod():$queryMethod($data)):$queryMethod;
    }
    initCache();
    global $cache;
    $cacheName = md5($name);
    if ($update) {
        goto set;
    }
    $cachedRes = $cache->get($cacheName);
    if ($cachedRes) {
        return $cachedRes;
    }
    set:
    $queryRes = is_object($queryMethod)?(empty($data)?$queryMethod():$queryMethod($data)):$queryMethod;
    $cache->set($cacheName, $queryRes, $timer);
    return $queryRes;
}
function getCache($name) {
    initCache();
    global $cache;
    $cacheName = md5($name);
    return $cache->get($cacheName);
}
function setCache($name,$queryMethod,$data = '',$timer = 3600) {
    initCache();
    global $cache;
    $cacheName = md5($name);
    $queryRes = is_object($queryMethod)?(empty($data)?$queryMethod():$queryMethod($data)):$queryMethod;
    $cache->set($cacheName, $queryRes, $timer);
    return $queryRes;
}
function clearCache() {
    initCache();
    global $cache;
    $cache->clearCache();
}
function removeCache($name) {
    initCache();
    global $cache;
    $name = md5($name);
    $cache->removeCache($name);
}
//去除空白字符
function trimAll($str) {
    $qian = array(" ","　","\t","\n","\r");
    $hou = array("","","","","");
    return str_replace($qian,$hou,$str);
}
//简写格式化输出
function p($var, $type = false) {
    if ($type) {
        var_dump($var);
    } else {
        print_r($var);
    }}
//json api模式
function jsonMsg($Msg) {
    header('Content-type:text/json');
    die(json_encode($Msg,JSON_UNESCAPED_UNICODE));
}
/**
 * 获取输入参数 支持过滤和默认值
 * 使用方法:
 * <code>
 * I('id',0); 获取id参数 自动判断get或者post
 * I('post.name','','htmlspecialchars'); 获取$_POST['name']
 * I('get.'); 获取$_GET
 * </code>
 * @param string $name 变量的名称 支持指定类型
 * @param mixed $default 不存在的时候默认值
 * @return mixed
 */
function I($name,$default = NULL) {
    if (strpos($name,'.')) {
        // 指定参数来源
        //判断参数$name中是否包括.号
        list($method,$name) = explode('.',$name,2);
        //如果包括.号将.号前后分隔，并且分别赋值给$method以及$name
    } else {
        // 默认为自动判断
        //如果没有.号
        $method = 'param';
    }
    switch (strtolower($method)) {
        //将$method转换为小写
        //如果$method为get，则$input为$_GET
        case 'get'     :  $input = str_replace(array('<','>', '"', "'"),array('&lt;','&gt;', '&quot;',''), $_GET);
            break;
            //如果$method为get，则$input为$_POST
        case 'post'    :  $input = str_replace(array('<','>', '"', "'"),array('&lt;','&gt;', '&quot;',''), $_POST);
        // }
            break;
            //如果为put，则将post的原始数据转参数给$input
        case 'put'     :   parse_str(file_get_contents('php://input'), $input);
            break;

        case 'gets'		:	$input =& $GLOBALS['gets'];
            break;

            //如果是param
        case 'param'   :
            //判断$_SERVER['REQUEST_METHOD']
            switch ($_SERVER['REQUEST_METHOD']) {
                //如果为post，则$input的内容为$_POST的内容
                case 'POST':
                    $input = str_replace(array('<','>', '"', "'"),array('&lt;','&gt;', '&quot;',''), $_POST);
                    break;
                    //如果为PUT.则input的内容为PUT的内容
                case 'PUT':
                    parse_str(file_get_contents('php://input'), $input);
                    break;
                    //默认为$_GET的内容
                default:
                    $input = str_replace(array('<','>', '"', "'"),array('&lt;','&gt;', '&quot;',''), $_GET);
            }
            break;
            //如果$method为request，则$input为$_REQUEST
        case 'request' :   $input =& $_REQUEST;
            break;
            //如果$method为session，则$input为$_SESSION
        case 'session' :   $input =& $_SESSION;
            break;
            //如果$method为cookie，则$input为$_COOKIE
        case 'cookie'  :   $input =& $_COOKIE;
            break;
            //如果$method为server，则$input为$_SERVER
        case 'server'  :   $input =& $_SERVER;
            break;
            //如果$method为globals，则$input为$GLOBALS
        case 'globals' :   $input =& $GLOBALS;
            break;
            //默认返回空
        default:
            return NULL;
    }
    /**
     * 到此为止，已经根据传入的参数的需要（第一个参数.号前面的），把所有的变量都取到了。下面就是返回变量的内容了。
     **/
    //如果$name为空，也就是I()第一个参数的.号后面为空的时候
    if ($name === NULL || $name === '') {
        // 获取全部变量
        //获取到的变量$input全部复制给$data
        $data = $input;
    } elseif (isset($input[$name])) {
        // 取值操作
        $data = $input[$name];
    } else {
        // 变量默认值
        $data = isset($default)?$default:NULL;
    }
    return $data;
}

//htlm字符编码
function htmlEncode($str,$prefix = '&#', $encoding = 'utf-8' , $postfix = ';') {
    //将字符串拆分
    $str = iconv("UTF-8", "gb2312", $str);
    $cind = 0;
    $arr_cont = array();
    for ($i = 0; $i < strlen($str); $i++) {
        if (strlen(substr($str, $cind, 1)) > 0) {
            if (ord(substr($str, $cind, 1)) < 0xA1) {
                //如果为英文则取1个字节
                array_push($arr_cont, substr($str, $cind, 1));
                $cind++;
            } else {
                array_push($arr_cont, substr($str, $cind, 2));
                $cind += 2;
            }
        }
    }
    foreach ($arr_cont as &$row) {
        $row = iconv("gb2312", "UTF-8", $row);
    }
    //转换Unicode码
    $unicodestr = '';
    foreach ($arr_cont as $key => $value) {
        $unicodestr.= $prefix . base_convert(bin2hex(iconv('utf-8', 'UCS-4', $value)), 16, 10) .$postfix;
    }
    return $unicodestr;
}
//文件上传
function upload($con=false){
    $config=c('upload');
    if(is_array($con)){
        $config=array_merge($config,$con);
    }
    
    //检查是否有文件
    if(empty($_FILES[$config['fileName']]['tmp_name'])){$err = '请选择需要上传的文件';goto err;}
    //检查扩展名
    $pathinfo=pathinfo($_FILES[$config['fileName']]['name']);
    $extName=$pathinfo['extension'];
    $config['fileType']=strtolower($config['fileType']);
    $config['fileExt']=strtolower($config['fileExt']);
    if(!is_integer(strpos($config['fileExt'], $extName))){$err = '上传文件扩展名错误';goto err;}
    //检查文件大小
    if($_FILES[$config['fileName']]['size'] > $config['maxSize']*1024){ $err = '上传文件的大小超过了'. $config['maxSize'] .'k';goto err;  }
    //检查文件类型
    if(!empty($config['fileType'])){
        if(!is_integer(strpos($config['fileType'], $_FILES[$config['fileName']]['type']))){$err = '上传文件类型错误';goto err;}
    }
    //检查目录
    if(!is_dir($config['savePath'])){mkdir($config['savePath'], 0777, true);}
    //上传
    if(move_uploaded_file($_FILES[$config['fileName']]['tmp_name'], $config['savePath'].$config['saveName'].'.'.$extName)){
        return $config['showPath'].$config['saveName'].'.'.$extName;
    }
    $err='文件上传失败';
    err:
    if(is_object($config['err']))$config['err']($err);return false;
}
function is_ajax(){
    if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"){ 
        return true;
    }else{ 
        return false;
    };
}
function is_post(){
    //判断form数据是否为POST而来，判断数据提交方式
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        return true;
    } else {
        return false;
    }
}
function is_weixin(){ 
if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false )
    {
        return true;
    }  
        return false;

}
//判断是否是网址
function is_url($v){
	$pattern="#(http|https)://(.*\.)?.*\..*#i";
	if(preg_match($pattern,$v)){ 
		return true; 
	}else{ 
		return false; 
	} 
}
//判断是否手机
function is_mobile() {
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
        Return true;
    }
    if (!isset($_SERVER['HTTP_USER_AGENT'])) {
        Return false;
    }
    $waparray = array('android','iphone','ipad','mobile');
    foreach ($waparray as $thisphone) {
        if (stripos($_SERVER['HTTP_USER_AGENT'],$thisphone) === false) {} else {
            Return true;
        }
    }
    Return false;
}
//错误页面
function M_err($title,$msg = '',$icon = '3',$url = 1,$btn = '确定') {
    switch ($icon) {
        case 1:$icon = 'weui-icon-success weui-icon_msg';
            break;
        case 2:$icon = 'weui-icon-info weui-icon_msg';
            break;
        case 3:$icon = 'weui-icon-info weui-icon_msg-primary';
            break;
        case 4:$icon = 'weui-icon-warn weui-icon_msg';
            break;
        case 5:$icon = 'weui-icon-waiting weui-icon_msg';
            break;
        default:$icon = 'weui-icon-warn weui-icon_msg-primary';
            break;
    }
    switch ($url) {
        case 1:$url = 'javascript:history.go(-1)';
            break;
        case 2:$url = 'javascript:location.reload()';
            break;
    }
    include(M_IN.'templates'.M_DS.'err.php');
    exit;
}
//获得ip
function M_ip() {
    if (isset($_SERVER)) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($arr as $ip) {
                $ip = trim($ip);
                if ($ip != 'unknown') {
                    $realip = $ip;
                    break;
                }
            }
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        } else {
            if (isset($_SERVER['REMOTE_ADDR'])) {
                $realip = $_SERVER['REMOTE_ADDR'];
            } else {
                $realip = '0.0.0.0';
            }
        }
    } else {
        if (getenv('HTTP_X_FORWARDED_FOR')) {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('HTTP_CLIENT_IP')) {
            $realip = getenv('HTTP_CLIENT_IP');
        } else {
            $realip = getenv('REMOTE_ADDR');
        }
    }
    preg_match("/[\d\.]{7,15}/",$realip,$onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
    return $realip;
}
//生成订单号
function M_order() {
    $order_id_main = date('YmdHis') . rand(10000000,99999999);

    $order_id_len = strlen($order_id_main);

    $order_id_sum = 0;

    for ($i = 0; $i < $order_id_len; $i++) {

        $order_id_sum += (int)(substr($order_id_main,$i,1));

    }
    return  $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
}
//获取顶级域名
function M_topHost($url,$type = 0) {
    if (!$url) {
        return FALSE;
    }
    $url = strtolower($url);
    //首先转成小写
    $hosts = parse_url($url);
    if ($type == 0) {
        $host = $hosts['path'];
    } else {
        $host = $hosts['host'];
    }
    //查看是几级域名
    $data = explode('.', $host);
    $n = count($data);
    //判断是否是双后缀
    $preg = '/[\w].+\.(com|net|org|gov|edu)\.cn$/';
    if (($n > 2) && preg_match($preg, $host)) {
        //双后缀取后3位
        $host = @$data[$n - 3] . '.' . @$data[$n - 2] . '.' . @$data[$n - 1];
    } else {
        //非双后缀取后两位
        $host = @$data[$n - 2] . '.' . @$data[$n - 1];
    }
    return $host;
}

/***自定义函数***/
//随机生成数
function M_rand($length = 6,$type = 1) {

    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        $password .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    return $password;
}
// run log
function M_runLog() {
    if (!Debug) {
        return false;
    }
    $cost = M_cost();
    echo '<script>console.log("MTFY Log : 控制器 : '.M_C.
    ', 方法 : '.M_M.' - 运行时间 : '. $cost[0] .'毫秒, 占用内存 : ' . $cost[1] .'k");</script>';
}
/**
 * 时间、内存开销计算
 * @return array(耗时[毫秒], 消耗内存[K])
 */
function M_cost() {
    return array(
        round((microtime(true) - 系统开始运行时间) * 1000, 2),
        round((memory_get_usage() - 内存初始) / 1024, 2)
    );
}



function 获取URL() {
    if (isset($_SERVER['HTTP_X_ORIGINAL_URL'])) {
        $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_ORIGINAL_URL'];
    } elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
        $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];
    } elseif (isset($_SERVER['HTTP_REQUEST_URI'])) {
        $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_REQUEST_URI'];
    }
    return $_SERVER['REQUEST_URI'];
}
/**
 * 设置或配置信息
 * 配置1，设置文件地址，只设置一项则返回配置文件信息
 * 配置2，设置保存数组，追加保存
 */
function 配置信息($config_file,$new_config = null) {
    if ($new_config) {
        if (is_file($config_file) && is_writable($config_file)) {
            $config = require $config_file;
            $config = array_merge($config, $new_config);
            file_put_contents($config_file, "<?php \nreturn " . stripslashes(var_export($config, true)) . ";", LOCK_EX);
            return true;
        } else {
            return false;
        }
    } else {
        if (is_file($config_file)) {
            return @require $config_file;
        }
        return false;
    }
}